package reflect;

import reflect.annotation.AutoRunClass;
import reflect.annotation.AutoRunMethod;

import java.io.File;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.URISyntaxException;

/**
 * 调用与当前类Test5所在同一个包中被注解@AutoRunClass标注的类中那些被注解@AutoRunMethod标注的方法
 */

public class Test5 {
    public static void main(String[] args) throws URISyntaxException, ClassNotFoundException, InvocationTargetException, IllegalAccessException, InstantiationException {
        //获取test5所在的路径
        File dir=new File(Test5.class.getResource(".").toURI());
        //获取包名
        String packName=Test5.class.getPackage().getName();
        File[] files=dir.listFiles(f->f.getName().endsWith(".class"));
        for (File file:files){
            String fileName=file.getName();
            String className=fileName.substring(0,fileName.indexOf("."));
            Class cls=Class.forName(packName+"."+className);

            if (cls.isAnnotationPresent(AutoRunClass.class)){
                Object obj=cls.newInstance();
                Method[] methods=cls.getDeclaredMethods();
                for (Method method:methods){
                    if(method.isAnnotationPresent(AutoRunMethod.class)){
                        System.out.println(method.getName()+"被标注了");
                        method.invoke(obj);
                    }else{
                        System.out.println(method.getName()+"没有被标注");
                    }

                }
            }
        }

    }
}
